package com.example.demo.util;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * Jasypt加解密工具类
 */
public class JasyptUtil {

    /**
     * 加密
     * @param password 加密盐值
     * @param value 需要加密的内容
     * @return
     */
    public static String encyptPassword(String password,String value){
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        encryptor.setConfig(cryptor(password));
        String result = encryptor.encrypt(value);
        return result;
    }

    /**
     * 解密
     * @param password 加密盐值
     * @param value 密文
     * @return
     */
    public static String decyptPassword(String password,String value){
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        encryptor.setConfig(cryptor(password));
        String result = encryptor.decrypt(value);
        return result;
    }

    /**
     * 配置
     * @param password
     * @return
     */
    public static SimpleStringPBEConfig cryptor(String password){
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        return config;
    }

    public static void main(String[] args) {
        //待加密内容
        String waitEncyptStr = "123456";
        System.out.println("待加密内容=" + waitEncyptStr);

        //加密
        String encyptPassword = encyptPassword("my_salt", waitEncyptStr);
        System.out.println("加密后内容=" + encyptPassword);

        //解密
        String decyptPassword = decyptPassword("my_salt", encyptPassword);
        System.out.println("解密后内容=" + decyptPassword);

    }
}

